package com.laicunba.ext.web.controller.h5.activity;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.laicunba.event.RateIncrCouponCreateEvent;
import com.laicunba.ext.web.controller.SuiCunBaoBaseController;
import com.laicunba.pojo.RateIncrCouponDO;
import com.laicunba.pojo.RateIncrCouponDefDO;
import com.laicunba.pojo.RegistryDO;
import com.laicunba.pojo.UserDO;
import com.laicunba.service.RateIncrCouponDefService;
import com.laicunba.service.RegistryService;
import com.laicunba.util.StringUtil;

@Controller
@RequestMapping(value = "/h5/ext/activity")
public class MonthlyInvestController extends SuiCunBaoBaseController {
	private static final Logger LOG = Logger.getLogger(MonthlyInvestController.class);
	
	@Autowired
	private RegistryService registryService;
	@Autowired
	private RateIncrCouponDefService rateIncrCouponDefService;
	 
	@RequestMapping(value = "/monthly_invest_{actid}.htm")
	public ModelAndView monthlyInvest(@PathVariable("actid") String id ) {
		ModelAndView view = new ModelAndView("august_monthly.jsp");
		RegistryDO registryDO = registryService.get(RegistryDO.class, "sys.monthly-invest." + id);
		if(registryDO == null) {
			return view;
		}
		
		try {
			JSONObject incrConfig = (JSONObject)new JSONParser().parse(registryDO.getVal());
			view.addObject("incrConfig", incrConfig);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return view;
	}
	
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/monthly_receive_rate_incr.htm")
	public String monthlyReceiveRateIncr(HttpServletRequest request) {
		UserDO loginUser = getCurrentUser(request);
		JSONObject json = new JSONObject();
		if(loginUser == null) {
			json.put("code", "LOGIN_TIME_OUT");
			json.put("msg", "登录超时");
			return json.toJSONString();
		}
		
		String period = request.getParameter("period");
		if(StringUtil.isEmpty(period)) {
			json.put("code", "PARAM_ERROR");
			json.put("msg", "参数错误");
			return json.toJSONString();
		}

		try{
			DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			RegistryDO onOffRegistry = registryService.get(RegistryDO.class, "act.monthly-invest.open");
			if(onOffRegistry != null) {
				JSONArray actTimeArray = (JSONArray)new JSONParser().parse(onOffRegistry.getVal());
				if(actTimeArray != null) {
					Map<String, String> tempMap = (Map<String, String>) actTimeArray.get(0);
					if(tempMap != null && new Date().compareTo(sdf.parse(tempMap.get("start_time"))) >= 1 && new Date().compareTo(sdf.parse(tempMap.get("end_time"))) < 1) {
						sdf = new SimpleDateFormat("yyyyMM");
						String ym = sdf.format(new Date());
						RegistryDO monthlyInvestRegistry = registryService.get(RegistryDO.class, "u."+loginUser.getId()+".monthly-invest." + ym);
						if(monthlyInvestRegistry != null) {
							LOG.info(String.format("【月月投活动】本月您已领取加息券，加息券未定义，registry_id为[%s]", "u."+loginUser.getId()+".monthly-invest." + ym));
							json.put("code", "RECEIVED_YET");
							json.put("msg", "本月您已领取加息券");
							return json.toJSONString();
						}
						String incrRate = "";
						if("30".equals(period)) {
							incrRate = "0.5";
						} else if("50".equals(period)) {
							incrRate = "1";
						} else if("80".equals(period)) {
							incrRate = "2";
						} else {
							incrRate = "0";
						}
						RateIncrCouponDefDO rateIncrDef = rateIncrCouponDefService.get(RateIncrCouponDefDO.class, "act-monthly-invest-rate-incr-" + incrRate);
						if (rateIncrDef == null) {
							LOG.error(String.format("【月月投活动】发放加息券出错，加息券未定义，rateIncrDef为[%s]，加息利率为[%s]", rateIncrDef, incrRate));
							json.put("code", "FAIL");
							json.put("msg", "领取失败");
							return json.toJSONString();
						} else if(rateIncrDef.getUsedQuantity() >= rateIncrDef.getTotalQuantity() || (rateIncrDef.getEndTime() != null && new Date().after(rateIncrDef.getEndTime()))) {
							LOG.error(String.format("【月月投活动】发放加息券出错，加息券已发完或加息券信息已过期，已发放[%s]张，发行量为[%s]，加息券定义结束时间为[$s]，当前时间为[%s]", rateIncrDef.getUsedQuantity(), rateIncrDef.getTotalQuantity(), rateIncrDef.getEndTime(), new Date()));
							json.put("code", "FAIL");
							json.put("msg", "领取失败");
							return json.toJSONString();
						} else {
							RateIncrCouponDO rateIncrCoupon = rateIncrCouponDefService.send2User(rateIncrDef.getId(), loginUser.getId(), false, "用户在活动期间投资定期理财送加息券");
							RateIncrCouponCreateEvent rateIncrEvent = new RateIncrCouponCreateEvent(rateIncrCoupon);
							applicationEventPublisher.publishEvent(rateIncrEvent);
							//标记用户已发放加息券
							monthlyInvestRegistry = new RegistryDO();
							monthlyInvestRegistry.setId("u."+loginUser.getId()+".monthly-invest." + ym);
							monthlyInvestRegistry.setVal("1");
							monthlyInvestRegistry.setVisible(true);
							boolean createState = registryService.create(monthlyInvestRegistry);
							
							if(rateIncrCoupon != null && createState) {
								LOG.info(String.format("【月月投活动】加息券领取成功，加息券id为[%s],加息额度为[%s]", rateIncrCoupon.getId(), rateIncrCoupon.getRate()));
								json.put("code", "SUCCESS");
								json.put("msg", "领取成功");
								return json.toJSONString();
							} else {
								LOG.info(String.format("【月月投活动】加息券领取失败，加息券对象为[%s],领取标记状态为[%s]", rateIncrCoupon, createState));
								json.put("code", "FAIL");
								json.put("msg", "领取失败");
								return json.toJSONString();
							}
						}
					}
				}
			}
			json.put("code", "FAIL");
			json.put("msg", "领取失败，活动未开始或已结束");
			return json.toJSONString();
		}catch(Exception e){
			LOG.error(String.format("【月月投活动】发放加息券出错，系统异常", e));
			json.put("code", "FAIL");
			json.put("msg", "本月您已领取加息券");
			return json.toJSONString();
		}
	}
	
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/monthly_invest_login_status.htm")
	public String monthlyInvestLoginStatus(HttpServletRequest request){
		JSONObject json = new JSONObject();
		UserDO user = getCurrentUser(request);
		if(user == null) {
			json.put("loginStatus", 0);
		} else {
			json.put("loginStatus", 1);
		}
		return json.toJSONString();
	}
	
}
